package com.t3go.t3_map.business.valuation;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.shareware.common.ApplicationKt;
import com.shareware.common.utils.LogExtKt;
import com.shareware.common.utils.ScreenExtKt;
import com.t3go.passenger.base.utils.DensityUtil;
import com.t3go.passenger.base.utils.JsonUtils;
import com.t3go.passenger.base.utils.ViewUtils;
import com.t3go.t3_map.R;
import com.t3go.t3_map.business.common.MapHelper;
import com.t3go.t3_map.entity.Annotation;
import com.t3go.t3_map.entity.ValuationArgs;
import com.t3go.t3_map.entity.BubbleBean;
import com.t3go.t3_map.entity.ImageBean;
import com.t3go.t3_map.entity.TextBean;
import com.t3go.t3_map.entity.TextsEntity;
import com.t3go.t3_map.utils.MapUtils;
import com.t3go.t3_map.utils.StyleUtils;
import com.t3map.api.T3MapsInitializer;
import com.t3map.api.map.T3Map;
import com.t3map.api.map.model.T3LatLng;
import com.t3map.api.map.model.T3Marker;
import com.t3map.api.map.model.T3MarkerOptions;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ValuationMapHelper extends MapHelper {

    private static final String TAG = "ValuationMapHelper";
    /**
     * 起终点图标，针尖到顶部的比例
     */
    public static final float ANCHOR_Y = 0.86f;
    public static final float ICON_HEIGHT = ScreenExtKt.dp2px(28);
    public static final float ANCHOR_TOP = ICON_HEIGHT * ANCHOR_Y;


    public ValuationMapHelper(Context context, T3Map map) {
        super(context, map);
    }

    public List<T3Marker> addBubble(Annotation data) {
        if (data == null || data.getArgs() == null) {
            return null;
        }
        ValuationArgs args = JsonUtils.fromJson(JsonUtils.toJson(data.getArgs()), ValuationArgs.class);

        if (args == null || args.getBubble() == null) {
            LogExtKt.log(TAG, "addBubble -> error, args is null.");
            return null;
        }
        T3LatLng position = new T3LatLng(data.getLatitude(), data.getLongitude());
        T3Marker iconMarker = addIconMarker(position, data.getzIndex(), args.getImage());
        T3Marker contentMarker = addContentMarker(position, data.getzIndex(), args.getBubble());

        List<T3Marker> markers = new ArrayList<>();
        if (iconMarker != null) {
            markers.add(iconMarker);
        }
        if (contentMarker != null) {
            markers.add(contentMarker);
        }

        return markers;
    }

    private T3Marker addIconMarker(T3LatLng latLng, int zIndex, ImageBean image) {
        if (image == null || TextUtils.isEmpty(image.getImageName())) {
            return null;
        }
        View iconView = buildIconView(image.getImageName());
        T3MarkerOptions options = new T3MarkerOptions()
                .position(latLng)
                .iconView(iconView)
                .draggable(false)
                .zIndex(zIndex)
                .setFlat(false)
                .infoWindowEnable(false)
                .anchor(0.5f, ANCHOR_Y);

        T3Marker marker = null;
        if (mMap != null) {
            marker = mMap.addMarker(options);
        }
        if (marker != null) {
            marker.hideInfoWindow();
            marker.setClickable(false);
        }
        return marker;
    }

    private View buildIconView(String iconPath) {
        ViewGroup view = (ViewGroup) LayoutInflater.from(ApplicationKt.getContextGlobal()).inflate(R.layout.valuation_marker_bubble_icon, null);
        ImageView imageView = view.findViewById(R.id.image_marker);
        imageView.setImageBitmap(loadImageFromAssets(mContext, MapUtils.getAssetPath(iconPath)));
        return view;
    }

    private T3Marker addContentMarker(T3LatLng latLng, int zIndex, BubbleBean data) {
        View view = buildNowBubbleView(data);
        float anchorY = getAnchorY(view, ANCHOR_TOP, 1f) + 1;
        T3MarkerOptions options = new T3MarkerOptions()
                .position(latLng)
                .iconView(view)
                .draggable(false)
                .zIndex(zIndex)
                .setFlat(false)
                .anchor(0.5f, anchorY);

        T3Marker marker = mMap.addMarker(options);
        if (marker != null) {
            marker.hideInfoWindow();
            marker.setClickable(true);
        }
        return marker;
    }

    private View buildNowBubbleView(BubbleBean bubble) {
        View view = View.inflate(mContext, R.layout.valuation_marker_bubble_content, null);
        View timeView = view.findViewById(R.id.view_time);
        TextView timeText = view.findViewById(R.id.text_time);
        TextView noteText = view.findViewById(R.id.text_time_note);
        TextView titleText = view.findViewById(R.id.tv_marker_title);
        TextView tipsText = view.findViewById(R.id.tv_stop_tips);
        View modifyView = view.findViewById(R.id.view_modify);
        View lineView = view.findViewById(R.id.view_line);

        TextsEntity texts = bubble.getTexts();
        if (texts == null) {
            return view;
        }
        TextBean time = texts.getTime();
        TextBean timeTips = texts.getTimeTips();
        if (time != null && timeTips != null) {
            timeView.setVisibility(View.VISIBLE);
            lineView.setVisibility(View.VISIBLE);
            StyleUtils.setTextStyle(timeText, time);
            StyleUtils.setTextStyle(noteText, timeTips);
        } else {
            timeView.setVisibility(View.GONE);
            lineView.setVisibility(View.GONE);
        }

        StyleUtils.setTextStyle(titleText, texts.getContent());

        modifyView.setVisibility(bubble.isShowArrow() ? View.VISIBLE : View.GONE);

        TextBean stopInfo = texts.getStopInfo();
        if (stopInfo != null && !TextUtils.isEmpty(stopInfo.getText())) {
            tipsText.setVisibility(View.VISIBLE);
            StyleUtils.setTextStyle(tipsText, stopInfo);
        } else {
            tipsText.setVisibility(View.GONE);
        }
        int maxWidth = DensityUtil.dp2px(118);
        int tipWidth = ViewUtils.getWidth(tipsText);
        if (tipWidth > maxWidth) {
            maxWidth = tipWidth;
        }
        titleText.setMaxWidth(maxWidth);
        return view;
    }

    public void updateBubble(List<T3Marker> markers, Annotation annotation) {
        if (markers == null || annotation == null || annotation.getArgs() == null) {
            return;
        }
        ValuationArgs args = JsonUtils.fromJson(JsonUtils.toJson(annotation.getArgs()), ValuationArgs.class);
        if (args == null || args.getBubble() == null) {
            LogExtKt.log(TAG, "updateBubble -> error, args is null.");
            return;
        }

        LogExtKt.log(TAG, "updateBubble -> marker size = " + markers.size());
        if (markers.size() != 2) {
            return;
        }
        T3LatLng position = new T3LatLng(annotation.getLatitude(), annotation.getLongitude());

        // 图标
        T3Marker iconMarker = markers.get(0);
        updateIconMarker(iconMarker, position, annotation.getzIndex(), args.getImage());
        iconMarker.setObject(annotation);

        // 气泡
        T3Marker contentMarker = markers.get(1);
        updateContentMarker(contentMarker, position, annotation.getzIndex(), args.getBubble());
        contentMarker.setObject(annotation);
    }

    private void updateIconMarker(T3Marker marker, T3LatLng position, int zIndex, ImageBean image) {
        if (image == null || TextUtils.isEmpty(image.getImageName())) {
            return;
        }
        View iconView = buildIconView(image.getImageName());
        marker.setView(iconView);
        marker.setPosition(position);
        marker.setZIndex(zIndex);
    }

    private void updateContentMarker(T3Marker marker, T3LatLng position, int zIndex, BubbleBean data) {
        View view = buildNowBubbleView(data);
        float anchorY = getAnchorY(view, ANCHOR_TOP, 1f) + 1;
        marker.setView(view);
        if (anchorY != marker.getAnchorV()) {
            if (T3MapsInitializer.getMapType() == T3MapsInitializer.MAP_TYPE_AMAP) {
                marker.setAnchor(0.5f, anchorY);
            } else {
                // TODO
                // 腾讯地图不支持，原生是通过重新添加marker的方式实现
            }
        }
        marker.setPosition(position);
        marker.setZIndex(zIndex);
    }

    private static float getAnchorY(@NonNull View view, float marginBottom, float devValue) {
        float height = view.getHeight();
        if (height == 0) {
            view.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            height = view.getMeasuredHeight();
        }
        if (height > 0) {
            return marginBottom / height;
        }
        return devValue;
    }

    private Bitmap loadImageFromAssets(Context context, String path) {
        Bitmap bitmap = null;
        try {
            InputStream is = context.getAssets().open(path);
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return bitmap;
        } catch (Exception e) {
            Log.d(TAG, "loadImageFromAssets e = " + e);
            e.printStackTrace();
        }
        return bitmap;
    }
}
